<?php
class arraytoxml {
private function __constract() {
// Nothing to do
}
 
private function putheade() {
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control:post-check=0,pre-check=0",false);
header("Pragma: no-cache");
header("Content-type: text/xml; charset=UTF-8");

}
 private function structDom($dom, $data, $result,$item) {
if (is_array($data)) {
 
// 因为XML节点名不能为纯数字，所以这里需要进行一下判断
foreach ($data as $key => $value) {
if (is_numeric($key)) {
$tagName = $item;
} else {
$tagName = $key;
}
 
// 递归转换为XML
if (is_array($value)) {
$keyElement = $dom->createElement($tagName);
$result->appendChild($keyElement);
self::structDom($dom, $value, $keyElement,$item);
} else {
$keyElement = $dom->createElement($tagName);
$keyElement->appendChild($dom->createTextNode($value));
$result->appendChild($keyElement);
}
}
return $result;
}
}
public function getXML($data=null,$root="Lists",$item="Item") {
// $data必须是数组
//if ($data == null || !is_array($data) || count($data) == 0) return false;
 
// 生成DOM对象
$dom = new DOMDocument('1.0','utf-8');
 
// 创建DOM根元素
$resultElement = $dom->createElement($root);
 
// 循环组织DOM元素
self::structDom($dom, $data, $resultElement,$item);
 
// 将创建完成的DOM元素加入DOM对象
$dom->appendChild($resultElement);
 
// 输出header

 
// 输出XML
return $dom->saveXML();
}
 

}

?>